package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserLoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    private static final String url = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public UserLoginVO userLogin(UserLoginDTO userLoginDTO) {
        String openid = userOpenid(userLoginDTO);
        if (openid == null) {
            throw new UserNotLoginException(MessageConstant.LOGIN_FAILED);
        }
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setOpenid(openid);

     User getuser= userMapper.getClass(openid);
        User user = new User();
        user.setOpenid(openid);
        user.setCreateTime(LocalDateTime.now());


        if (getuser==null){
      User user1=   userMapper.addUser(user);
     }
        userLoginVO.setId(getuser.getId());

        return userLoginVO;
    }

    private String userOpenid(UserLoginDTO userLoginDTO){
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        String s = HttpClientUtil.doGet(url, paramMap);
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
